<?php

//运程定义控制器
class Haul_define_mainApp extends BackendApp
{
	var $_haul_define_main_mod;

    var $_haul_define_mod;

	var $_haul_define_collect_mod;

    var $_operator_mod;

	function __construct()
	{
		$this->Haul_define_mainApp();
	}

	function Haul_define_mainApp()
	{
		parent::BackendApp();

		$this->_haul_define_main_mod =& m ('haul_define_main');

        $this->_haul_define_mod =& m ('haul_define');

		$this->_haul_define_collect_mod =& m('haul_define_collect');

        $this->_operator_mod =& m ('operator');

	}


	function index()
	{

		$types=array();
		$types['集卡进口'] = '集卡进口';
		$types['集卡出口'] = '集卡出口';
		$types['整车'] = '整车';
		$types['零担'] = '零担';
		$types['城配'] = '城配';
		$this->assign('types', $types);

		$zhdm_name=empty($_GET['zhdm_name'])?'':$_GET['zhdm_name'];
		$zhdm_type=empty($_GET['zhdm_type'])?'':$_GET['zhdm_type'];
		$conditions = "1=1 ";
		if($zhdm_name){
			$conditions.=" and zhdm_name like '%".$zhdm_name."%'";
		}
		if($zhdm_type){
			$conditions.=" and zhdm_type = '".$zhdm_type."'";
		}
        $user_ids = $this->checkpower();
        if(!empty($user_ids)){
            $conditions.=" and zhdm_userid in(".$user_ids.")";
        }
		$page   =   $this->_get_page(10);   //获取分页信息
		$haul_define_main=$this->_haul_define_main_mod->find(array(
	        'fields'   => 'this.*', 
		    'conditions'  => $conditions,
	        'limit'   => $page['limit'],
			'order'   => 'zhdm_tid desc',
		//'join'=>'belongs_to_dictionary',
        	'count'   => true   //允许统计
		));    //找出所有的运单
		$page['item_count']=$this->_haul_define_main_mod->getCount();   //获取统计数据
        foreach($haul_define_main as $key=>$val){
            $zhdm_otid = $val['zhdm_otid'];
            if(!empty($zhdm_otid)){
                $ot_info = $this->_operator_mod->get_info($zhdm_otid);
                $haul_define_main[$key]['carrier_name'] = $ot_info['o_name'];
            }else{
                $haul_define_main[$key]['carrier_name'] ='所有运营商';
            }
            $zhdm_consignor = $val['zhdm_consignor'];
            if(!empty($zhdm_consignor)){
                $com_info = $this->_operator_mod->get_info($zhdm_consignor);
                $haul_define_main[$key]['consignor_name'] = $com_info['o_name'];
            }else{
                $haul_define_main[$key]['consignor_name'] = '所有货主';
            }
        }
		$this->_format_page($page);
		$this->assign('page_info', $page);   //将分页信息传递给视图，用于形成分页条
		$this->assign('haul_define_main', $haul_define_main);
		$this->assign('tabself', json_encode(array('text'=>'运程方案')));
		$this->display('haul_define_main.index.html');
	}


    //添加/编辑-运程方案------fhc
    function add()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $types=array();
        $db=&db();
        $sql="SELECT d_value FROM zys_dictionary WHERE d_code='waybiltype'";
        $temptypes=$db->getAll($sql);
        foreach ($temptypes as  $v){
            $types[$v['d_value']]=$v['d_value'];
        }
        //业务类型
        $this->assign('types', $types);
        if (!IS_POST)
        {
            $sql="SELECT o_tid,o_name FROM zys_operator WHERE o_consignor=1";
            $temp=$db->getAll($sql);
            $hz=array();
            if($temp){
                foreach ($temp as $v){
                    $hz[$v['o_tid']]=$v['o_name'];
                }
                $hz[0]="所有货主";
            }
            //货主
            $this->assign('hz', $hz);

            $sql="SELECT d_value,d_key FROM zys_dictionary WHERE d_code='haultype'";
            $haultype=array();
            $temp=$db->getAll($sql);
            foreach($temp as $val){
                $haultype[$val['d_key']] = $val['d_value'];
            }
            //确认类型
            $this->assign('haultype',$haultype);

            $sql="SELECT d_value,d_key FROM zys_dictionary WHERE d_code='h_collect_type'";
            $typelist=array();
            $temp=$db->getAll($sql);
            foreach ($temp as $v){
                $typelist[$v['d_key']]=$v['d_value'];
            }
            //操作类型
            $this->assign('ctype', $typelist);

            //运程方案数据
            $haul_define_main=$this->_haul_define_main_mod->get(array(
                'fields'   => 'this.*',
                'conditions'  => 'zhdm_tid='.$id,
            ));
            if($haul_define_main['zhdm_consignor']==0){
                $haul_define_main['zhdm_consignor_name'] = '所有货主';
            }else{
                $sql='select o_name from zys_operator where o_tid='.$haul_define_main['zhdm_consignor'];
                $o_name = $this->_operator_mod->getOne($sql);
                $haul_define_main['zhdm_consignor_name'] = $o_name;
            }
            //运程定义数据
            $sql="SELECT * FROM zys_haul_define WHERE h_zhdmtid=$id order by h_order asc";
            $haul_define_main['haul']=$db->getAll($sql);
            //运程定义采集数据
            if($haul_define_main['haul']){
                foreach ($haul_define_main['haul'] as $k=>$v){
                    $hc_h_tid = $v['h_tid'];
                    $sql="SELECT * FROM zys_haul_define_collect WHERE hc_h_tid=$hc_h_tid";
                    $haul_define_main['haul'][$k]['hc_haul'] = $db->getAll($sql);
                }
            }
            /* 导入jQuery的表单验证插件 */
            $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js,jquery.plugins/jquery.validate.js',
                'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            $this->assign('haul_define_main', $haul_define_main);
            $this->assign('tabself', json_encode(array('text'=>'编辑方案')));
            $this->assign('tabback', json_encode(array('text'=>'运程方案','url'=>'')));
            $this->display('haul_define_main.form.html');
        }else {
            //获取当前用户信息
            $users = $this->visitor->get();

            if(empty($_POST['zhdm_type'])){
                if($id){
                    $this->show_warning('请选择业务类型', '',   'index.php?app=haul_define_main&act=add&id=' . $id);
                }else{
                    $this->show_warning('请选择业务类型', '',   'index.php?app=haul_define_main&act=add');
                }
                return;
            }
            if(empty($_POST['zhdm_name'])){
                if($id){
                    $this->show_warning('请填写运程定义名称', '',   'index.php?app=haul_define_main&act=add&id=' . $id);
                }else{
                    $this->show_warning('请填写运程定义名称', '',   'index.php?app=haul_define_main&act=add');
                }
                return;
            }
            if(empty($_POST['haul'])){
                if($id){
                    $this->show_warning('请填写运程定义', '',   'index.php?app=haul_define_main&act=add&id=' . $id);
                }else{
                    $this->show_warning('请填写运程定义', '',   'index.php?app=haul_define_main&act=add');
                }
                return;
            }

            $data = array(
                'zhdm_name' => $_POST['zhdm_name'],
                'zhdm_type'  => $_POST['zhdm_type'],
                'zhdm_otid'  => $users['unit'],
                'zhdm_consignor' => $_POST['zhdm_consignor'],
                'zhdm_note' => $_POST['zhdm_note'],
                'zhdm_time' => gmtime(),
                'zhdm_userid' => $users['user_id']
            );
            
            try{
                /* 保存运程方案信息 */
                if($id){
                	 $tag=1;
                    //修改
                    //判断是否此人添加
                    $sql='select zhdm_userid from zys_haul_define_main where zhdm_tid='.$id;
                    $zhdm_userid = $this->_haul_define_main_mod->getOne($sql);

                   /* if($zhdm_userid !=  $users['user_id']){
                        throw new Exception('您无权操作');
                    }*/
                    $this->_haul_define_main_mod->edit($id, $data);

                }else{
                    //添加
                     $tag=2;
                    $id = $this->_haul_define_main_mod->add($data);
                    if(empty($id)){
                        throw new Exception('操作失败');
                    }
                }

                //添加运程定义和采集
                $haul=empty($_POST['haul'])?array():$_POST['haul'];
                if($haul){
                    $haul=array_values($haul);
                    foreach ($haul as $k=>$v){
                        if(substr( $v['h_date'], 0, 1 ) == '@'){
                            $date = $v['h_date'];
                        }else{
                            $date = gmstr2time($v['h_date']);
                        }
                        $haul_sub = array(
                            'h_zhdmtid' => $id,
                            'h_short_name' => $v['h_short_name'],
                            'h_name' => $v['h_name'],
                            'h_type'  => intval($v['h_type']),
                            'h_linkman'  => $v['h_linkman'],
                            'h_linkman_tel'  => $v['h_linkman_tel'],
                            'h_date'  => $date,
                            'h_address'  => $v['h_address'],
                            'h_order'  => intval($v['h_order']),
                            'h_range'  => intval($v['h_range']),
                            'h_required'  => intval($v['h_required']),
                        );
                        if($v['h_tid']){
                            //修改
                            $h_tid = $v['h_tid'];
                            $this->_haul_define_mod->edit($h_tid, $haul_sub);
                            if ($this->_haul_define_mod->has_error())
                            {
                                throw new Exception($this->_haul_define_mod->get_error());
                            }
                        }else{
                            //添加
                            $h_tid = $this->_haul_define_mod->add($haul_sub);
                            if(empty($h_tid)){
                                throw new Exception('操作失败');
                            }
                        }
                        if($v['item']){
                            $v['item']=array_values($v['item']);
                            foreach ($v['item'] as $kk=>$vv){
                                $haul_collect = array(
                                    'hc_h_tid' => $h_tid,
                                    'h_collect_type' => intval($vv['h_collect_type']),
                                    'h_collect_des' =>  $vv['h_collect_des'],
                                    'h_collect_val' =>  $vv['h_collect_val'],
                                );
                                if($vv['hc_tid']){
                                    //修改
                                    $this->_haul_define_collect_mod->edit($vv['hc_tid'],$haul_collect);
                                }else{
                                    //添加
                                    $hc_tid = $this->_haul_define_collect_mod->add($haul_collect);
                                    if(empty($hc_tid)){
                                        throw new Exception('操作失败');
                                    }
                                }
                            }
                        }
                        unset($haul_sub);
                    }
                }
                if ($this->_haul_define_collect_mod->has_error())
                {
                    throw new Exception($this->_haul_define_collect_mod->get_error());
                }
                
                
                if ($tag==1){
               	
                	   $this->show_message('编辑成功',
                    '',   'index.php?app=haul_define_main&act=add&id=' . $id
                );
                }elseif ($tag==2) {
                  		   $this->show_message('添加成功',
                    '',   'index.php?app=haul_define_main&act=add&id=' . $id
                     );
                }
             
            }catch (Exception $e){
                if($id){
                    $this->show_warning($e->getMessage(), '',   'index.php?app=haul_define_main&act=add&id=' . $id);
                }else{
                    $this->show_warning($e->getMessage(), '',   'index.php?app=haul_define_main&act=add');
                }
                return;
            }
        }
    }

    //联系人参照
    function chooseman(){
        $db=&db();
        $type=$_GET['type'];
        $id=$_GET['id'];
        $this->assign('id', $id);
        $conditions = "d_del = 1";
        switch($type){
            case '集卡进口':
                $conditions .= " and  d_code = 'TI_man_refer'";
                break;
            case '集卡出口':
                $conditions .= " and  d_code = 'TE_man_refer'";
                break;
            case '整车':
                $conditions .= " and  d_code = 'C_man_refer'";
                break;
            case '零担':
                $conditions .= " and  d_code = 'L_man_refer'";
                break;
        }
        $sql="SELECT * FROM zys_dictionary WHERE $conditions";
        $man =$db->getAll($sql);
        $this->assign('man',$man);
        $this->display('haul_define_main.chooseman.html');
    }
    //联系电话参照
    function choosetel(){
        $db=&db();
        $type=$_GET['type'];
        $id=$_GET['id'];
        $this->assign('id', $id);
        $conditions = "d_del = 1";
        switch($type){
            case '集卡进口':
                $conditions .= " and  d_code = 'TI_tel_refer'";
                break;
            case '集卡出口':
                $conditions .= " and  d_code = 'TE_tel_refer'";
                break;
            case '整车':
                $conditions .= " and  d_code = 'C_tel_refer'";
                break;
            case '零担':
                $conditions .= " and  d_code = 'L_tel_refer'";
                break;
        }
        $sql="SELECT * FROM zys_dictionary WHERE $conditions";
        $tel =$db->getAll($sql);
        $this->assign('tel',$tel);
        $this->display('haul_define_main.choosetel.html');
    }
    //地址参照
    function chooseaddress(){
        $db=&db();
        $type=$_GET['type'];
        $id=$_GET['id'];
        $this->assign('id', $id);
        $conditions = "d_del = 1";
        switch($type){
            case '集卡进口':
                $conditions .= " and  d_code = 'TI_place_refer'";
                break;
            case '集卡出口':
                $conditions .= " and  d_code = 'TE_place_refer'";
                break;
            case '整车':
                $conditions .= " and  d_code = 'C_place_refer'";
                break;
            case '零担':
                $conditions .= " and  d_code = 'L_place_refer'";
                break;
        }
        $sql="SELECT * FROM zys_dictionary WHERE $conditions";
        $address =$db->getAll($sql);
        $this->assign('address',$address);
        $this->display('haul_define_main.chooseaddress.html');
    }
    //时间参照
    function choosetime(){
        $db=&db();
        $type=$_GET['type'];
        $id=$_GET['id'];
        $this->assign('id', $id);
        $conditions = "d_del = 1";
        switch($type){
            case '集卡进口':
                $conditions .= " and  d_code = 'TI_date_refer'";
                break;
            case '集卡出口':
                $conditions .= " and  d_code = 'TE_date_refer'";
                break;
            case '整车':
                $conditions .= " and  d_code = 'C_date_refer'";
                break;
            case '零担':
                $conditions .= " and  d_code = 'L_date_refer'";
                break;
        }
        $sql="SELECT * FROM zys_dictionary WHERE $conditions";
        $times =$db->getAll($sql);
        $this->assign('times',$times);
        $this->display('haul_define_main.choosetime.html');
    }
	//删除采集信息
	function drop_haul_define_collect()
	{
        $id = isset($_POST['id']) ? trim($_POST['id']) : '';
        if(empty($id)){
            $this->json_result(array(),'操作错误');
        }
        if (!$this->_haul_define_collect_mod->drop($id))
        {
            $this->json_error($this->_haul_define_mod->get_error());
            return;
        }
        $this->json_result(array(),'删除成功');
	}

	//删除运程定义
	function drophaul()
	{
        try{
            $db=&db();
            $h_tid = isset($_POST['id']) ? trim($_POST['id']) : '';

            if(empty($h_tid)){
                throw new Exception('操作失败');
            }
            $sql = "delete from zys_haul_define_collect where hc_h_tid=".$h_tid;
            $db->query($sql);

            $sql = "delete from zys_haul_define where h_tid=".$h_tid;
            $db->query($sql);

            $this->json_result(array(),'删除成功');

        }catch (Exception $e){
            $this->json_error($e->getMessage());
        }
	}
    //删除运程方案
    function drop(){
        $arr = isset($_GET['id']) ? trim($_GET['id']) : '';
        $db=&db();
        $arrs=explode(',', $arr);
        $ids = implode(',',array_filter($arrs));
        if($arrs!=null&&count($arrs)>0){
            try{
                $sql = "select h_tid from zys_haul_define where h_zhdmtid in(".$ids.")";
                $h_tids = $db->getAll($sql);
                foreach($h_tids as $val){
                    $h_tid = $val['h_tid'];

                    $sql_haul_define_collect = "delete from zys_haul_define_collect where hc_h_tid=".$h_tid;
                    $db->query($sql_haul_define_collect);

                    $sql_haul_define = "delete from zys_haul_define where h_tid=".$h_tid;
                    $db->query($sql_haul_define);
                }
                $sql_haul = "delete from zys_haul_define_main where zhdm_tid in(".$ids.")";
                $db->query($sql_haul);
                $this->show_message('删除成功',	'', 'index.php?app=haul_define_main&act=index');
            }catch (Exception $e){
                $this->json_error($e->getMessage());
            }
        }else{
            $this->show_message('请选择删除项',	'', 'index.php?app=haul_define_main&act=index');
        }
    }
}